<!--
  多图上传组件
  @author: haoxr
  @date 2022/11/20
  @link https://element-plus.gitee.io/zh-CN/component/upload.html
-->

<template>
    <el-upload
        v-model:file-list="fileList"
        list-type="picture-card"
        :multiple="multiple"
        :before-upload="handleBeforeUpload"
        :http-request="handleUpload"
        :on-preview="handlePreview"
        :limit="props.limit"
    >
        <el-icon><Plus /></el-icon>
    </el-upload>

    <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import {
    ElMessage,
    ElUpload,
    UploadRawFile,
    UploadRequestOptions,
    UploadUserFile,
    UploadFile,
    UploadProps
} from 'element-plus';

//import { uploadFileApi, deleteFileApi,showFileApi } from '@/api/file';
//import { uploadFile as uploadFileApi } from '@/api/common';
//import { Import as uploadFileApi } from '@/api/buildingLeads/serverCenter';

import request from '@/utils/request';

const emit = defineEmits(['update:modelValue', 'Update']);

const props = defineProps({
    /**
     * 文件路径集合
     */
    modelValue: {
        type: Array<string>,
        default: [] as Array<string>
    },
    /**
     * 文件上传数量限制
     */
    limit: {
        type: Number,
        default: 5
    },
    /**
     * 是否多选
     */
    multiple: { type: Boolean, default: true },
    url: {
        type: String,
        default: '/admin/api/file/upload'
    }
});

const dialogImageUrl = ref('');
const dialogVisible = ref(false);

const fileList = ref([] as UploadUserFile[]);
watch(
    () => props.modelValue,
    (newVal: string[]) => {
        console.log('newVal', newVal);
        const filePaths = fileList.value.map((file) => file.url);
        // 监听modelValue文件集合值未变化时，跳过赋值
        if (
            filePaths.length > 0 &&
            filePaths.length === newVal.length &&
            filePaths.every((x) => newVal.some((y) => y === x)) &&
            newVal.every((y) => filePaths.some((x) => x === y))
        ) {
            return;
        }

        fileList.value = newVal.map((filePath) => {
            return { url: filePath } as UploadUserFile;
        });
    },
    { immediate: true }
);

/**
 * 自定义图片上传
 *
 * @param params
 */
async function handleUpload(options: UploadRequestOptions): Promise<any> {
    console.log(options);

    const res = await uploadFileApi(options.file);

    /*
    //回显图片
    const res = await showFileApi(fileId);
    const base64 = arrayBufferToBase64(res);


    // 上传成功需手动替换文件路径为远程URL，否则图片地址为预览地址 blob:http://
    const fileIndex = fileList.value.findIndex(
        file => file.uid == (options.file as any).uid
    );

    fileList.value.splice(fileIndex, 1, {
        name: ''+fileId,
        url: base64,
    } as UploadUserFile);*/

    emit(
        'update:modelValue',
        fileList.value.map((file) => file.url)
    );

    //emit('Update',fileList);
    emit('Update', res);
}

function arrayBufferToBase64(buffer: any) {
    var binary = '';
    var bytes = new Uint8Array(buffer);
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    const base64 = 'data:image/png;base64,' + btoa(binary); //这里需要添加前缀
    return base64;
}

function uploadFileApi(file: File) {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('remark', '');
    return request({
        url: props.url, //'/admin/api/partyBranch/import',
        method: 'post',
        data: formData,
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    });
}

/**
 * 删除图片

function handleRemove(removeFile: UploadFile) {
  const filePath = removeFile.url;

  if (filePath) {
    deleteFileApi(filePath).then(() => {
      // 删除成功回调
      emit(
        'update:modelValue',
        fileList.value.map(file => file.url)
      );

      emit( 'Update',fileList);

    });
  }
}*/

/**
 * 限制用户上传文件的格式和大小
 */
function handleBeforeUpload(file: UploadRawFile) {
    if (file.size > 2 * 1048 * 1048) {
        ElMessage.warning('上传图片不能大于2M');
        return false;
    }
    return true;
}

/**
 * 图片预览
 */
const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!;
    dialogVisible.value = true;
};
</script>
